const fs = require('fs');
const path = require('path');
const axios = require('axios');
const archiver = require('archiver');
const sdk = require('@baiducloud/sdk');
const BosClient = sdk.BosClient;

// 设置输入和输出目录
const INPUT_DIR = path.join(__dirname, 'configs');
const OUTPUT_DIR = path.join(__dirname, 'dist');

// 指定不想压缩的文件或目录
const EXCLUDE_FILES = [
    'demo.json',
    'detection.json'
].map((exclude) =>
    path.resolve(INPUT_DIR, exclude)
);

// 指定想要拷贝的文件或目录
const INCLUDE_FILES = [];

// 检测路径是否应该被排除
function shouldExclude(filePath) {
    return EXCLUDE_FILES.some((excludedPath) => filePath === excludedPath || filePath.startsWith(`${excludedPath}${path.sep}`));
}

// 递归获取所有js和json文件
function getFiles(dir) {
    let jsFiles = [];
    let jsonFiles = [];
    const items = fs.readdirSync(dir);

    items.forEach((item) => {
        const fullPath = path.join(dir, item);
        if (shouldExclude(fullPath)) {
            return;
        }
        const stat = fs.statSync(fullPath);
        if (stat.isFile() && item.endsWith('.js')) {
            jsFiles.push(fullPath);
        } else if (stat.isFile() && item.endsWith('.json')) {
            jsonFiles.push(fullPath);
        } else if (stat.isDirectory()) {
            let files = getFiles(fullPath);
            jsFiles = jsFiles.concat(files.jsFiles);
            jsonFiles = jsonFiles.concat(files.jsonFiles);
        }
    });

    return { jsFiles, jsonFiles };
}

const config = {
    endpoint: 'http://bd.bcebos.com',
    credentials: {
        ak: '6356708ce8d342bf965f2047d7c3cdb2',
        sk: 'd4837f696fdf4cf4abf11a80a1067abb'
    }
};

// BOS相关操作
const bucket = 'label-anything';
const client = new BosClient(config);

async function uploadFileToBOS(localFilePath, remoteFileName) {
    try {
        const response = await client.putObjectFromFile(bucket, remoteFileName, localFilePath);
        // console.log(`${remoteFileName} uploaded successfully`);
        return response;
    } catch (error) {
        console.error(`Failed to upload ${remoteFileName}:`, error);
        throw error;
    }
}

async function main() {
    // 获取所有JS文件，并执行压缩和混淆操作
    let files = getFiles(INPUT_DIR);

    // 上传所有的json文件到dist目录中
    files.jsonFiles.forEach(async (file) => {
        const relativePath = path.relative(INPUT_DIR, file);
        let remotePath = `/labelapp/pipeline/configs/${relativePath}`;
        await uploadFileToBOS(file, remotePath);
        console.log(`## File ${relativePath} uploaded to BOS.`);
    });
    console.log('## Deploy pipeline configs OK!');
}

main();
